package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.pojo.Orderform;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author H
 * @create 2020-10-15 16:34
 * @Description: 支付宝支付
 */
@RestController
public class PayController {
    @RequestMapping("/pay")
    public void doPost(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse
    ) throws ServletException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2016102600763079", "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCKhKsHLWEqhYRL8F8LBFOvS0h+cPfF7MDXtEqhkhI4qLYfQep5UeiFGtAoY2xhIfwB3bZZjwj4C592zeMASSultraWhxR/Cs4vjRBrgFtIhCbu/E+F8pZd7RxmlReYUpsuzTQSck+my1CSlfSPHmyoupN9NNvF0FauZZ8op5RzfpveEnG+gU2o7M0nsFLGMSWvmpwO8UmmiwGp3n84qhgWmAGsnGjIB+vA1i/6aYidXhYxuPc9BeEdaAtaSKa7yWrKwXy0ClUQfbfuIXuUVhWdElCuYzb1qW6Of96si2BjaJcpDCvRBOZmdJqIJ8pWWDMYzXz75z8SglzrTzwJ9G6pAgMBAAECggEBAIaUo36TroYbtw/4+L7Bc3Uq1cJTi8g3YJ2yw5f7TczSzi/MYT2CQUGhbYDwKEqvNCO0AAk/mV02HbbWDqkmbkvRG9FgaJ+OJgm5KqznxsjL7O/hIHpp2YJkb2WTkZsjFzb/l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\n" +
                "\n", "json", "utf-8", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAorqi1PVf0Li2fl4D3e5vrDcgqi37a6LQZbFn7hbpKn8atKiEvj7gqxqbiPaHtQ4TdkgK3cpFHsjqEbblJvEf4SVta6jY+WZtOjvwawqjPyl6MY8y/JpPqpNhEWHiTXm4Pyi7c9C4Ml6TwQ4y9fup2vAfBXkFixQItivY9zv+cdtZV1VE+RRJkht0wY/91mmkFmc4WFpNwu3My8ZvTAa+QxdBh5X6On7T4DK+BCsX+tXJUpmQEsAbCyjYW0YeAVpFPTeyXEn2R/S1r1OQjnZql9t7soBLhiOZTd2vAWIDP/gQq2cXVJ+f/9kUWnaYs/jIspsWEpO7Tt71H1Jq3vknfwIDAQAB", "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        //支付回调
        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\"20150320010101001\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "    \"total_amount\":456,"  +
                "    \"subject\":\"清热\","  +
                "    \"body\":\"清热\","  +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","  +
                "    \"extend_params\":{"  +
                "    \"sys_service_provider_id\":\"2088511833207846\""  +
                "    }" +
                "  }" ); //填充业务参数
        String form= "" ;
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + "utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping("/returnUrl")
    public void returnUrl(HttpServletRequest httpRequest,
                          HttpServletResponse httpResponse) throws AlipayApiException {
        Map<String, String> stringStringMap = requestParamsToMap(httpRequest);
        boolean signVerified = AlipaySignature.rsaCheckV1(stringStringMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAorqi1PVf0Li2fl4D3e5vrDcgqi37a6LQZbFn7hbpKn8atKiEvj7gqxqbiPaHtQ4TdkgK3cpFHsjqEbblJvEf4SVta6jY+WZtOjvwawqjPyl6MY8y/JpPqpNhEWHiTXm4Pyi7c9C4Ml6TwQ4y9fup2vAfBXkFixQItivY9zv+cdtZV1VE+RRJkht0wY/91mmkFmc4WFpNwu3My8ZvTAa+QxdBh5X6On7T4DK+BCsX+tXJUpmQEsAbCyjYW0YeAVpFPTeyXEn2R/S1r1OQjnZql9t7soBLhiOZTd2vAWIDP/gQq2cXVJ+f/9kUWnaYs/jIspsWEpO7Tt71H1Jq3vknfwIDAQAB", "utf-8", "RSA2"); //调用SDK验证签名
        if (signVerified) {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println(stringStringMap);
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

    private static Map<String, String> requestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;
            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

}
